package com.h3c.tj_nsh.Utils;

import android.util.Log;

import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest;

import java.io.IOException;
import java.net.HttpURLConnection;

/**
 *
 * 自定义拦截器，实现 DIGEST认证（从stackoverflow，大神手中抄袭）
 * Interceptor used to authorize requests.
 */
public class AuthorizationInterceptor implements Interceptor {

    private final DigestScheme digestScheme = new DigestScheme();
    private final Credentials credentials;

    public AuthorizationInterceptor(String username, String password) throws IOException, ClassNotFoundException {
        credentials = new UsernamePasswordCredentials(username, password);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Response response = chain.proceed(request);

        if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {

            String authHeader = buildAuthorizationHeader(response);
            if (authHeader != null) {
                request = request.newBuilder()
                        .addHeader("Authorization", authHeader)
                        .addHeader("accept","application/json")
                        .build();

                response = chain.proceed(request);

                if (response.code() == HttpURLConnection.HTTP_BAD_REQUEST || response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    response = chain.proceed(request);
                }
            }
        }

        return response;

    }

    private String buildAuthorizationHeader(Response response) throws IOException {
        processChallenge("WWW-Authenticate", response.header("WWW-Authenticate"));
        return generateDigestHeader(response);
    }

    private void processChallenge(String headerName, String headerValue) {
        try {
            digestScheme.processChallenge(new BasicHeader(headerName, headerValue));
        } catch (MalformedChallengeException e) {
            Log.e("AuthInterceptor", "Error processing header " + headerName + " for DIGEST authentication.");
            e.printStackTrace();
        }
    }

    private String generateDigestHeader(Response response) throws IOException {
        HttpRequest request = new BasicHttpRequest(
                response.request().method(),
                response.request().uri().toString()
        );

        try {
            return digestScheme.authenticate(credentials, request).getValue();
        } catch (AuthenticationException e) {
            Log.e("AuthInterceptor", "Error generating DIGEST auth header.");
            e.printStackTrace();
            return null;
        }
    }
}